<template>
  <!-- 若类型为数字则为数字输入框 -->
  <n-input-number
    v-if="type === 0"
    placeholder=""
    :disabled="field == `ID`"
    :show-button="false"
    @update:value="(n) => $emit(`update:value`, n)"
    :value="value"
    class="input"
  />
  <!-- 若字段为详细，则为富文本编辑器 -->
  <div v-else-if="field === `Detail`" style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      mode="simple"
    />
    <Editor
      style="height: 300px; overflow-y: hidden"
      @update:modelValue="(n) => $emit(`update:value`, n)"
      :modelValue="value"
      mode="simple"
      @onCreated="handleCreated"
      :default-config="editConfig"
    />
  </div>
  <!-- 若字段为图片，则为上传 -->
  <n-upload
    :showFileList="false"
    strong
    secondary
    class="upload"
    v-else-if="field === `ImgUrl`"
    @before-upload="beforeUpload"
    :custom-request="customUpload"
  >
    <div class="wrapper">
      <n-button ghost type="info">点击上传封面</n-button>
      <n-input class="input" placeholder="" disabled :value="value" />
    </div>
  </n-upload>
  <!-- 若类型为文本，则为普通输入框 -->
  <n-input
    v-else-if="type === ``"
    placeholder=""
    @update:value="(n) => $emit(`update:value`, n)"
    :value="value"
    class="input"
  />
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  NInput,
  NInputNumber,
  NUpload,
  NButton,
  UploadFileInfo,
  useMessage,
} from "naive-ui";
import { shallowRef, ref } from "vue";
import { upload } from "@/api";

defineProps<{
  field: any;
  type: any;
  value: any;
}>();

const emit = defineEmits(["update:value"]);

const message = useMessage();

async function beforeUpload(data: { file: UploadFileInfo }) {
  if (
    data.file.file?.type !== "image/png" &&
    data.file.file?.type !== "image/jpeg" &&
    data.file.file?.type !== "image/gif"
  ) {
    message.error("暂不支持的文件类型，请重新上传");
    return false;
  }
  return true;
}

async function customUpload({ file }: { file: any }) {
  const { msg, path } = await upload(file.file);
  message.success(msg);
  emit("update:value", path);
}

const editorRef = shallowRef();
const editConfig = ref({
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: Function) {
        const { path, msg } = await upload(file);
        message.success(msg);
        insertFn(path, null, null);
      },
    },
  },
});
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style lang="less" scoped>
.input {
  flex: 1;
}

.wrapper {
  display: flex;
}
</style>
